import { useMap } from '@/hooks';
import { useTheme } from '@/store/settingsStore.ts';
import { ThemeMode } from '@ycx/ui';
import { FC, useEffect, useMemo, useRef, useState } from 'react';
import MapBasicTool from '@/components/Map/components/MapBasicTool.tsx';
import ControlBar from '@/pages/historyReplay/components/ControlBar.tsx';
import InfoWindow from '@/pages/historyReplay/components/InfoWindow.tsx';
import {
  useCurrentIndex,
  useLocationData,
  useSetCurrentIndex,
  useTableIndex,
} from '@/store/locationStore.ts';

type Props = {
  carNo?: string;
  loading?: boolean;
};

const Map: FC<Props> = ({ carNo = '' }) => {
  const theme = useTheme();
  const locationData = useLocationData();
  const current = useCurrentIndex();
  const setCurrent = useSetCurrentIndex();
  const tableIndex = useTableIndex();
  const overlayRef = useRef<any[]>([]);
  const [isPlay, setIsPlay] = useState<boolean>(false);
  const [allCount, setAllCount] = useState(0);
  const lastTimeCurrent = useRef(0);
  const markerRef = useRef<AMap.Marker>();
  const path = useRef<[number, number][]>([]);
  const startOver = useRef(false);

  const {
    mapInstance,
    addCustomMarker,
    addPolyline,
    addText,
    editLayer,
    changePitch,
    changeZoom,
    zoomLevel,
  } = useMap({
    containerId: 'container',
    mapStyle: theme === ThemeMode.Light ? 'amap://styles/whitesmoke' : 'amap://styles/grey',
    center: [87.6177, 43.7928],
  });

  const destroy = () => {
    markerRef.current?.stopMove();
    if (overlayRef.current.length > 0) {
      mapInstance.current?.remove(overlayRef.current);
      overlayRef.current = [];
    }
    setCurrent(0);
    setAllCount(0);
    lastTimeCurrent.current = 0;
    setIsPlay(false);
    markerRef.current = undefined;
    path.current = [];
    startOver.current = false;
  };

  const startMove = (index = 0) => {
    try {
      const p = path.current.slice(index);
      if (p.length > 1) {
        markerRef.current?.moveAlong(path.current.slice(index), {
          // 每一段的时长
          duration: 300, //可根据实际采集时间间隔设置
          // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
          autoRotation: true,
        });
      }
    } catch (e) {
      console.log(e);
    }
  };

  const handleMoving = (e: any) => {
    mapInstance.current?.setCenter(e.target.getPosition(), true);
  };

  const handleRestart = () => {
    markerRef.current?.stopMove();
    markerRef.current?.setPosition(path.current?.[0]);
    mapInstance.current?.setCenter(path.current?.[0], true);
    lastTimeCurrent.current = 0;
    setCurrent(0);
    setIsPlay(false);
    startOver.current = true;
  };

  const handlePlay = () => {
    if (startOver.current) {
      // startMove(current);
      startMove(current);
    } else {
      markerRef.current?.resumeMove();
    }
    startOver.current = false;
    setIsPlay(true);
  };

  const handlePause = () => {
    markerRef.current?.pauseMove();
    setIsPlay(false);
  };

  const handleChange = (index: number) => {
    setCurrent(index);
    lastTimeCurrent.current = index;
    if (isPlay) markerRef.current?.stopMove();
    const nextPosition = path.current[index];
    markerRef.current?.setPosition(nextPosition);
    mapInstance.current?.setCenter(nextPosition);
    if (isPlay) {
      startMove(index);
    } else {
      startOver.current = true;
    }
  };

  useEffect(() => {
    if (locationData.length > 0) {
      const alarmData = locationData.filter((i) => i.alarmDesc);
      alarmData.forEach((alarm) => {
        const icon = new AMap.Icon({
          image:
            'https://uconcern.oss-cn-chengdu.aliyuncs.com/statics/freight/historical-replay/alarm.png',
        });

        const alarmMarker = addCustomMarker({
          position: [alarm.longitude, alarm.latitude],
          icon: icon,
          offset: new AMap.Pixel(-12, -56),
          extData: alarm,
        });

        alarmMarker.on('click', () => {
          const index = locationData.findIndex((i) => i.alarmId === alarm.alarmId);
          handleChange(index);
        });

        overlayRef.current.push(alarmMarker);
      });

      const _path = locationData.map((i) => [i.longitude, i.latitude]);
      const line = addPolyline(_path);
      const startPoint = addText({
        content: '起点',
        position: _path[0] as [number, number],
        style: {
          width: '32px',
          height: '24px',
          'border-radius': '4px',
          color: 'var(--ycx-font-color-l2)',
          display: 'flex',
          'justify-content': 'center',
          'align-items': 'center',
          'font-size': '12px',
          'font-weight': '500',
          border: 'none',
          'background-color': 'var(--ycx-color-green-pale)',
        },
      });
      const endPoint = addText({
        content: '终点',
        position: _path[_path.length - 1] as [number, number],
        style: {
          width: '32px',
          height: '24px',
          'border-radius': '4px',
          color: 'var(--ycx-font-color-l2)',
          'background-color': 'var(--ycx-primary-color-pale )',
          display: 'flex',
          'justify-content': 'center',
          'align-items': 'center',
          'font-size': '12px',
          'font-weight': '500',
          border: 'none',
        },
      });
      const icon = new AMap.Icon({
        image:
          'https://uconcern.oss-cn-chengdu.aliyuncs.com/statics/freight/historical-replay/car.png',
        imageSize: new AMap.Size(64, 64),
      });

      const carMarker = addCustomMarker({
        position: _path[0] as [number, number],
        icon: icon,
        anchor: 'center',
      });

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      carMarker.on('moving', handleMoving);

      carMarker.on('moveend', (e) => {
        setCurrent(e.index + lastTimeCurrent.current);
      });

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      carMarker.on('movealong', () => {
        setIsPlay(false);
      });

      overlayRef.current.push(line, startPoint, endPoint, carMarker);

      markerRef.current = carMarker;
      setIsPlay(true);
      setAllCount(_path.length - 1);
      path.current = _path as [number, number][];

      setCurrent(0);
      startMove(0);
    }

    return destroy;
  }, [locationData]);

  useEffect(() => {
    if (typeof tableIndex === 'number') handleChange(tableIndex);
  }, [tableIndex]);

  const items = useMemo(() => {
    if (locationData.length === 0) return [];
    const data = locationData[current];
    return [
      { key: 'company', label: '巡检队', children: '--', span: 24 },
      {
        key: 'lat',
        label: '经纬度',
        children: `${data?.longitude}, ${data?.latitude}`,
        span: 24,
      },
      { key: 'address', label: '地理位置', children: data.address ?? '暂无', span: 24 },
      { key: 'deviceTime', label: '位置时间', children: data?.deviceTime ?? '暂无', span: 24 },
      { key: 'alarmDesc', label: '病害报警', children: data?.alarmDesc ?? '暂无', span: 24 },
    ];
  }, [current]);

  return (
    <div className="h-full">
      <div id="container" className="h-full" />
      <MapBasicTool
        editLayer={editLayer}
        editPitch={changePitch}
        zoomLevel={zoomLevel}
        onChangeZoom={(isZoomIn) => {
          changeZoom(isZoomIn);
        }}
      />
      {locationData.length > 1 && (
        <ControlBar
          isPlay={isPlay}
          onChange={handleChange}
          current={current}
          allCount={allCount}
          onRestart={handleRestart}
          onPlay={handlePlay}
          onPause={handlePause}
        />
      )}

      {locationData.length > 0 && (
        <InfoWindow
          data={{
            carNo: carNo,
            items: items,
            imgList: locationData[current]?.imageList,
          }}
          onClose={() => {}}
        />
      )}
    </div>
  );
};

export default Map;
